import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import moment from 'moment';
import { ProductGroupTreeC, PrimaryC, ModalC, TableC, NoQueryC } from '../../../comps';
import myStyle from './index.less';
import accounting from 'accounting';
import { findValueByCode } from '../../../utils/utils';
const FormItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 21 },
};
@connect(({ CreditAccountDetailM, globalM, loading }) => ({
  CreditAccountDetailM,
  globalM,
  loading,
}))
@Form.create()
export default class ShowModalC extends PureComponent {
  state = {
    columns: undefined,
    dataSource: undefined,
    columnsDefault: [
      { title: '产品名称', key: 'productName' },
      { title: '组合名称', key: 'portfolioName' },
      { title: '保证金占用', key: 'occupy', type: 'money' },
      { title: '类型', key: 'largeUnilateralType' },
    ],
    portfolioId: undefined,
    expandedRowKeys: [], //默认展开项
  };
  //计算多头空头总和
  calcSum = (data) => {
    if (!data || (data && !data.length)) return '--';
    let sum = data.reduce((x, y) => x + y.marginMoney, 0);
    return accounting.formatNumber(sum, 2);
  };
  //子项展示
  expandedRowRender = (record) => {
    if (!record.occupy) return null;
    return (
      <div className={myStyle.childDiv}>
        <div className={myStyle.itemDiv}>
          <div className={myStyle.title}>多头：{this.calcSum(record.childDataDuoTou)}</div>
          <div className={`${myStyle.cols} ${myStyle.colstitle} `}>
            <p>合约代码</p>
            <p>保证金</p>
          </div>
          <div className={myStyle.scrollH}>
            {record.childDataDuoTou &&
              record.childDataDuoTou.map((item, key) => {
                return (
                  <div className={myStyle.cols} key={key}>
                    <p title={item.tradingCode + '-' + item.tradingName}>{item.tradingCode + '-' + item.tradingName}</p>
                    <p title={accounting.formatNumber(item.marginMoney, 2)}>{accounting.formatNumber(item.marginMoney, 2)}</p>
                  </div>
                );
              })}
          </div>
        </div>
        <div>
          {' '}
          {record.largeUnilateralType == 1 ? (
            <img src={require('../../../assets/busi/investmentAndDecision/dayu.png')} />
          ) : (
            <img src={require('../../../assets/busi/investmentAndDecision/xiaoyu.png')} />
          )}
        </div>
        <div className={myStyle.itemDiv}>
          <div className={myStyle.title}>空头：{this.calcSum(record.childDataKongTou)} </div>
          <div className={`${myStyle.cols} ${myStyle.colstitle} `}>
            <p>合约代码</p>
            <p>保证金</p>
          </div>
          <div className={myStyle.scrollH}>
            {record.childDataKongTou &&
              record.childDataKongTou.map((item, key) => {
                return (
                  <div className={myStyle.cols} key={key}>
                    <p title={item.tradingCode + '-' + item.tradingName}>{item.tradingCode + '-' + item.tradingName}</p>
                    <p title={accounting.formatNumber(item.marginMoney, 2)}>{accounting.formatNumber(item.marginMoney, 2)}</p>
                  </div>
                );
              })}
          </div>
        </div>
      </div>
    );
  };
  renderTable = () => {
    const { columns, dataSource } = this.state;
    const scrollY = document.body?.offsetHeight - 250 || undefined;
    const {
      globalM: {
        dataDictionary: { MAAT_FUT_STOCKTYPE = [] },
      },
    } = this.props;
    columns &&
      columns.map((item) => {
        if (item.key == 'largeUnilateralType') {
          item.render = (text) => {
            return findValueByCode(text, MAAT_FUT_STOCKTYPE);
          };
        }
      });
    return (
      <TableC
        columns={columns}
        dataSource={dataSource}
        expandedRowRender={(record) => this.expandedRowRender(record)}
        expandedRowKeys={this.state.expandedRowKeys}
        onExpandedRowsChange={(expandedRows) => {
          this.setState({ expandedRowKeys: [...expandedRows] });
        }}
        rowClassName={(record) => (record?.occupy ? '' : myStyle.noExpend)} //无子项 设置样式
        hidePage={true}
        scroll={{ y: scrollY }}
        rowKey={'key'}
      />
    );
  };
  //关闭弹窗
  cancel = () => {
    this.props.visibleChange(false);
  };
  portfolioChange = (e) => {
    let portfolioId;
    if (e) {
      portfolioId = [];
      e.info.map((item) => {
        portfolioId.push(item.portfolioCode);
      });
    } else {
      this.setState({
        columns: undefined,
        dataSource: undefined,
        expandedRowKeys: [],
      });
    }
    this.setState({ portfolioId }, () => {
      if (e) this.queryTableList();
    });
  };
  //查询列表
  queryTableList = () => {
    const { columnsDefault, expandedRowKeys } = this.state;
    this.setState({
      columns: undefined,
      dataSource: undefined,
    });
    this.props.dispatch({
      type: 'CreditAccountDetailM/queryMarginMoneyList',
      payload: {
        portfolioId: this.state.portfolioId,
      },
      callback: (data) => {
        if (data) {
          data.map((item, key) => {
            item.productName = item.productCode + '-' + item.productName;
            item.portfolioName = item.portfolioCode + '-' + item.portfolioName;
            item.tradingCode = item.tradingCode + '-' + item.tradingName;
            item.key = key;
            if (item.occupy) {
              //默认展开
              expandedRowKeys.push(item.key);
            }
          });

          this.setState({
            columns: [...columnsDefault],
            dataSource: data,
            expandedRowKeys: [...expandedRowKeys],
          });
        } else {
          this.setState({
            columns: [...columnsDefault],
            dataSource: [],
          });
        }
      },
    });
  };
  render() {
    const { visible } = this.props;
    return (
      <ModalC
        title={'当前保证金占用明细'}
        visible={visible}
        onCancel={this.cancel}
        width={980}
        height={document.body?.offsetHeight - 250}
        footer={null}
        maskClosable={false}
        wrapClassName={myStyle.myModal}
      >
        <div style={{ width: '344px' }}>
          <ProductGroupTreeC dataIndex='portfolioIds' title={'组合'} form={this.props.form} onChange={this.portfolioChange} formItemLayout={FormItemLayout} positionBody={true} />
        </div>
        {this.state.portfolioId ? this.renderTable() : <NoQueryC title={'请选择组合查询对应明细'} />}
      </ModalC>
    );
  }
}
